package com.ruoyi.patient.controller;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.patient.entity.LoginPatient;
import com.ruoyi.patient.entity.MyCartBody;
import com.ruoyi.patient.entity.cart.Datum;
import com.ruoyi.patient.service.MyCartService;
import com.ruoyi.patient.service.PatientTokenService;
import com.ruoyi.patient.utils.PatientTokenFilter;
import com.ruoyi.service.domain.ServiceMycart;
import com.ruoyi.service.service.IServiceComboService;
import com.ruoyi.service.service.IServiceItemsService;
import com.ruoyi.service.service.IServiceMycartService;
import com.ruoyi.service.service.IServicePackagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车控制类
 *
 * @author ZDL
 */

@RestController
@RequestMapping("/appPatient/appPatientMyCart")
public class MyCartController {


    @Autowired
    private MyCartService myCartService;

    @Autowired
    private IServiceMycartService serviceMycartService;

    @Autowired
    private IServiceComboService serviceComboService;
    @Autowired
    private IServiceItemsService serviceItemsService;
    @Autowired
    private IServicePackagesService servicePackagesService;

    @Autowired
    private PatientTokenService tokenService;

    @Autowired
    private PatientTokenFilter patientTokenFilter;


    /**
     * 购物车新增方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/addMyCart")
    public AjaxResult addMyCart(@RequestBody Map<String, Long> reqBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            Long itemId = reqBody.get("itemId");
            Long comboId = reqBody.get("comboId");
            Long packageId = reqBody.get("packageId");
            Long num = reqBody.get("num");
            if (itemId == null || comboId == null || num == null) {
                return AjaxResult.warn("传入信息错误");
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient.getUserId() == null ) {
                return AjaxResult.warn("用户信息错误");
            }
            if (serviceItemsService.selectServiceItemsByItemId(itemId) == null) {
                return AjaxResult.warn("服务项目不存在");
            }
            if (serviceComboService.selectServiceComboByComboId(comboId) == null) {
                return AjaxResult.warn("服务套餐不存在");
            }
            //if (servicePackagesService.selectServicePackagesByPackagesId(packageId) == null) {
            //    return AjaxResult.warn("耗材包不存在");
            //}
            ServiceMycart searchCart = new ServiceMycart();
            searchCart.setMycartUserid(oldPatient.getUserId());
            searchCart.setMycartItemid(itemId);
            searchCart.setMycartComboid(comboId);
            searchCart.setMycartPackageid(packageId);
            List<ServiceMycart> oldCart = serviceMycartService.selectServiceMycartList(searchCart);
            ServiceMycart newCart = null;
            if (oldCart.size() > 0){
                newCart = myCartService.addMyCart(oldCart.get(0), itemId, comboId, packageId, num, oldPatient);
            }else{
                newCart = myCartService.addMyCart(null, itemId, comboId, packageId, num, oldPatient);
            }
            if (newCart != null){
                Map<String, Object> data = new HashMap<>();
                data.put("cartId", newCart.getMycartId());
                return AjaxResult.success("添加成功", data);
            }
            return AjaxResult.error("添加失败");
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 购物车修改方法
     *
     * @param myCartBody 购物车操作信息
     * @return 结果
     */
    @PostMapping("/updateMyCart")
    public AjaxResult updateMyCart(@RequestBody MyCartBody myCartBody, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            if (!"1".equals(myCartBody.getFlag())) {
                return AjaxResult.warn("操作无效");
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient.getUserId() == null || oldPatient.getUserId() != myCartBody.getUserId()) {
                return AjaxResult.warn("用户信息错误");
            }
            if (Long.parseLong(myCartBody.getNum()) < 0) {
                return AjaxResult.warn("数量不能小于0");
            }
            if (serviceComboService.selectServiceComboByComboId(myCartBody.getItemId()) == null) {
                return AjaxResult.warn("服务不存在");
            }
            List<ServiceMycart> serviceMycart = serviceMycartService.selectServiceMycartByMycartUserId(myCartBody.getUserId());
            int okFlag = 0;
            for (ServiceMycart mycart : serviceMycart) {
                if (mycart.getMycartItemid().equals(myCartBody.getItemId())) {
                    if (myCartService.updateMyCart(myCartBody, oldPatient)) {
                        okFlag = 1;
                        break;
                    }
                }
            }
            if (okFlag == 1){
                return AjaxResult.success("修改成功");
            }else {
                return AjaxResult.error("修改失败");
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 购物车删除方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/deleteMyCart")
    public AjaxResult deleteMyCart(@RequestBody Map<String, Long> reqBody, HttpServletRequest request) {
        try{
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            Long cartId = reqBody.get("cartId");
            if(cartId == null){
                return AjaxResult.warn("信息错误");
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient.getUserId() == null ) {
                return AjaxResult.warn("用户信息错误");
            }
            ServiceMycart delMyCart = serviceMycartService.selectServiceMycartByMycartId(cartId);
            if (delMyCart == null || delMyCart.getMycartUserid() != oldPatient.getUserId()) {
                return AjaxResult.warn("信息错误");
            }
            if (myCartService.deleteMyCartByMycartId(cartId)) {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                return AjaxResult.success("删除成功", data);
            } else {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", false);
                return AjaxResult.success("删除失败", data);
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }

    /**
     * 购物车查询方法
     *
     * @param
     * @return 结果
     */
    @GetMapping("/getMyCart")
    public AjaxResult getMyCart(Long hospId, Long userId, HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient.getUserId() == null) {
                return AjaxResult.warn("用户信息错误");
            }
            Datum myCart = myCartService.getMyCartDetail(oldPatient.getUserId());
            if(myCart == null){
                return AjaxResult.warn("购物车为空");
            }
            return AjaxResult.success("获取成功", myCart);
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 清空购物车方法
     *
     * @param
     * @return 结果
     */
    @PostMapping("/clearMyCart")
    public AjaxResult clearMyCart(HttpServletRequest request) {
        try {
            if(!patientTokenFilter.doFilterInternal(request)) {
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code", 401);
                ajaxResult.put("msg", "用户信息过期，请重新登录");
                return ajaxResult;
            }
            LoginPatient oldPatient = tokenService.getLoginUser(request);
            if (oldPatient.getUserId() == null ) {
                return AjaxResult.warn("用户信息错误");
            }

            if (myCartService.deleteMyCartAll(oldPatient)) {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", true);
                return AjaxResult.success("清空成功", data);
            } else {
                Map<String, Object> data = new HashMap<>();
                data.put("flag", false);
                return AjaxResult.success("清空失败", data);
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }

    }




}
